package com.huabo.contract.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hbfk.util.PageInfo;
import com.huabo.contract.config.DateBaseConfig;
import com.huabo.contract.oracle.entity.TblContractCollection;
import com.huabo.contract.oracle.entity.TblContractInvoicesmanagemen;
import com.huabo.contract.oracle.entity.TblContractPlannode;
import com.huabo.contract.oracle.entity.TblContractSpnode;
import com.huabo.contract.oracle.entity.TblCounterpartBankinfo;
import com.huabo.contract.oracle.entity.TblCyhwUnit;
import com.huabo.contract.oracle.entity.TblOrgBankaccount;
import com.huabo.contract.oracle.mapper.TblContractCollectionMapper;
import com.huabo.contract.oracle.mapper.TblContractInvoicesmanagemenMapper;
import com.huabo.contract.oracle.mapper.TblContractPlannodeMapper;
import com.huabo.contract.oracle.mapper.TblContractSpnodeMapper;
import com.huabo.contract.oracle.mapper.TblCounterpartBankinfoMapper;
import com.huabo.contract.oracle.mapper.TblCyhwUnitMapper;
import com.huabo.contract.oracle.mapper.TblOrgBankaccountMapper;
import com.huabo.contract.service.TblContractCollectionService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("TblContractCollectionService")
@Slf4j
public class TblContractCollectionServiceImpl implements TblContractCollectionService {

    @Resource
    private TblContractCollectionMapper tblContractCollectionMapper;
    @Resource
    private TblContractSpnodeMapper tblContractSpnodeMapper;
    @Resource
    private TblContractPlannodeMapper tblContractPlannodeMapper;
    @Resource
    private TblCyhwUnitMapper tblCyhwUnitMapper;
    @Resource
    private TblContractInvoicesmanagemenMapper tblContractInvoicesmanagemenMapper;
    @Resource
    private TblCounterpartBankinfoMapper tblCounterpartBankinfoMapper;
    
    @Resource
    private  TblOrgBankaccountMapper tblOrgBankaccountMapper;
    
    @Override
    public String findCollectionListByPageInfo(PageInfo<TblContractCollection> pageInfo, String staffid, String contractname, String contractno,BigDecimal pid, TblContractCollection collection) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            String result = null;
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractCollectionMapper.selectListByPageInfo(pageInfo, staffid, contractname, contractno, pid, collection));
            pageInfo.setTotalRecord(tblContractCollectionMapper.selectCountByPageInfo(staffid, contractname, contractno, pid, collection));

            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
            JSONObject jsonObject = new JSONObject(resultMap);
            result = jsonObject.toString();
            return result;
        } else {
            String result = null;
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractCollectionMapper.selectListByPageInfo(pageInfo, staffid, contractname, contractno, pid, collection));
            pageInfo.setTotalRecord(tblContractCollectionMapper.selectCountByPageInfo(staffid, contractname, contractno, pid, collection));

            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
            JSONObject jsonObject = new JSONObject(resultMap);
            result = jsonObject.toString();
            return result;
        }
    }

    @Override
    public Integer checkMoney(BigDecimal nodeId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return this.tblContractCollectionMapper.checkMoneyNodeId(nodeId);
        } else {
            return this.tblContractCollectionMapper.checkMoneyNodeId(nodeId);
        }
    }

    @Override
    public Integer getSkMoney(BigDecimal nodeId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return this.tblContractCollectionMapper.getSkMoneyNodeId(nodeId);
        } else {
            return this.tblContractCollectionMapper.getSkMoneyNodeId(nodeId);
        }
    }

    @Override
    public TblContractCollection findById(BigDecimal contractid) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return this.tblContractCollectionMapper.findByContractId(contractid);
        } else {
            return this.tblContractCollectionMapper.findByContractId(contractid);
        }
    }

    @Override
    public void mengerCollectionEntity(TblContractCollection oldCollection) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            this.tblContractCollectionMapper.UpdateOldCollection(oldCollection);
        } else {
            this.tblContractCollectionMapper.UpdateOldCollection(oldCollection);
        }
    }

    @Override
    public void SaveMengerCollectionEntity(TblContractCollection collection) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            this.tblContractCollectionMapper.SaveMengerCollectionEntity(collection);
        } else {
            this.tblContractCollectionMapper.SaveMengerCollectionEntity(collection);
        }
    }

    @Override
    public TblContractCollection findByCollectionId(Integer collectionId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return tblContractCollectionMapper.findByCollectionId(collectionId);
        } else {
            return tblContractCollectionMapper.findByCollectionId(collectionId);
        }
    }

    @Override
    public void removeContractCollection(Integer collectionId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            this.tblContractCollectionMapper.removeContractCollection(collectionId);
        } else {
            this.tblContractCollectionMapper.removeContractCollection(collectionId);
        }
    }

    @Override
    public TblContractCollection findCollectionInfoByCollectId(Integer collectionId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return tblContractCollectionMapper.findCollectionInfoByCollectId(collectionId);
        } else {
            return tblContractCollectionMapper.findCollectionInfoByCollectId(collectionId);
        }
    }

	@Override
	public String getSkContractIds() {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            // TODO Auto-generated method stub
            return tblContractCollectionMapper.getSkContractIds();
        } else {
            // TODO Auto-generated method stub
            return tblContractCollectionMapper.getSkContractIds();
        }
	}

	@Override
	public String setData(JSONArray arr) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            // TODO Auto-generated method stub
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (arr != null) {
                try {
                    for (Object j : arr) {
                        net.sf.json.JSONObject obj = (net.sf.json.JSONObject) j;
                        TblContractCollection cole =tblContractCollectionMapper.findByContract(obj.getString("def20"),obj.getString("def19"));
                        if(cole==null){
                        cole=new TblContractCollection();
                        cole.setCollectionbank(obj.getString("collectionbank"));
                        cole.setCollectionaccount(obj.getString("collectionaccount"));
                        cole.setCollectionskdate(obj.get("bill_date") != null ? sdf.parse(obj.get("bill_date").toString()) : null);
                        cole.setNodeid(new BigDecimal(obj.getString("def19")));
                        cole.setContractid(new BigDecimal(obj.getString("def20")));
                        cole.setNodemoney(obj.get("local_money") != null ? new BigDecimal(obj.get("local_money").toString()) : null);
                        cole.setCollectionstatus(TblContractCollection.STATE_WC);
                        TblCyhwUnit  unit=tblCyhwUnitMapper.findContractById(Integer.valueOf(cole.getContractid().toString()));
                        cole.setCreatestaff(unit.getCreateuser());
                        cole.setLinkorg(unit.getOrgid());
                      
                        //获取合同相对方 并查询是否有该银行账号 否则新增 
                        TblCounterpartBankinfo bank= tblCounterpartBankinfoMapper.selectBankInfoById(unit.getContractxdfxinfo().toString(),cole.getCollectionaccount());
                        TblOrgBankaccount count= tblOrgBankaccountMapper.findByBankNum(obj.getString("collectionaccount"),unit.getOrgid());
                        if(bank==null){
                            bank=new TblCounterpartBankinfo();
                            bank.setBankaccount(cole.getCollectionaccount());
                            bank.setBankkhyh(cole.getCollectionbank());
                            bank.setBanknature(new BigDecimal(0));
                            bank.setBankstatus(new BigDecimal(1));
                            bank.setCreatestaff(unit.getCreateuser());
                            bank.setCreatetime(new Date());
                            bank.setBudgetid(unit.getContractxdfxinfo());
                            tblCounterpartBankinfoMapper.saveBank(bank);
                         }
                        if(count==null){
                        	count= new TblOrgBankaccount();
                            count.setBankaccname(obj.getString("collectionbank"));
                            count.setBankcode(obj.getString("collectionaccount"));
                            count.setBankaccnum(obj.getString("collectionaccount"));
                            count.setBankkhyh(obj.getString("collectionbank"));
                            count.setBankstate(new BigDecimal(0));
                            count.setBankstatus(new BigDecimal(1));
                            count.setOrgid(unit.getOrgid());
                            count.setCreatedate(new Date());
                            tblOrgBankaccountMapper.savebankInfo(count);
                        }
                         cole.setCounterbank(bank.getBankid());
                         cole.setOrgbank(count.getBankid());
                         cole.setOrgBankName(bank.getBankaccname());
                        TblContractInvoicesmanagemen men=new TblContractInvoicesmanagemen();
                        men.setInvoiceno((new Date()).getTime()+"");
                        men.setInvoicemoney(obj.get("total") != null ? new BigDecimal(obj.get("total").toString()) : new BigDecimal(0));
                        men.setInvoicedate(obj.get("bill_date") != null ? sdf.parse(obj.get("bill_date").toString()) : null);
                     //   tblCyhwUnitMapper.updaContractStatus(unit.getContractid().toString(), 8);  验证合同收付款金额是否已经全部完成，验证合同履行阶段是否全部完成
//                        TblContractSpnode  spNode = new TblContractSpnode();
//                        spNode.setContractid(new BigDecimal(obj.getString("def20").toString()));
//                        spNode.setNodeid(new BigDecimal(obj.getString("def19").toString()));
//                         this.tblContractSpnodeMapper.saveBySpnode(spNode);
                        if (obj.getString("def19")!= null) {
                            TblContractPlannode node = tblContractPlannodeMapper.findBynodeId(Integer.valueOf(obj.getString("def19")));
//                            node.setPlannodestatus(new BigDecimal("2"));
//                            tblContractPlannodeMapper.updateContractPlannode(node);
                            men.setInvoicepost(new BigDecimal(node.getNodepost()));
                            men.setInvoicecontent(node.getNodecontent());
                        }
                        tblContractInvoicesmanagemenMapper.saveMergenEntity(men);
                        cole.setInvoiceid(men.getInvoiceid());
                        tblContractCollectionMapper.SaveMengerCollectionEntity(cole);
                    }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            } else {
                resultMap.put("code", "1");
                resultMap.put("msg", "失败！");
            }
            return resultMap.toString();
        } else {
            // TODO Auto-generated method stub
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (arr != null) {
                try {
                    for (Object j : arr) {
                        net.sf.json.JSONObject obj = (net.sf.json.JSONObject) j;
                        TblContractCollection cole = new TblContractCollection();
                        cole.setCollectionbank(obj.getString("collectionbank"));
                        cole.setCollectionaccount(obj.getString("collectionaccount"));
                        cole.setCollectionskdate(obj.get("paydate") != null ? sdf.parse(obj.get("paydate").toString()) : null);
                        cole.setNodeid(new BigDecimal(obj.getString("def19")));
                        cole.setContractid(new BigDecimal(obj.getString("def20")));
                        cole.setNodemoney(obj.get("local_money") != null ? new BigDecimal(obj.get("local_money").toString()) : null);
                        cole.setCollectionstatus(TblContractCollection.STATE_WC);
                        tblContractCollectionMapper.SaveMengerCollectionEntity(cole);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            } else {
                resultMap.put("code", "1");
                resultMap.put("msg", "失败！");
            }
            return resultMap.toString();
        }
	}

}
